package com.wangp.mywrite.s_netty.netty.ch2;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringEncoder;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import lombok.extern.slf4j.Slf4j;

import java.net.InetSocketAddress;
import java.util.Scanner;

/**
 * @author tooStronger
 * @date 2023/3/17
 */
@Slf4j
public class ChannelFutureCloseClient {

    public static void main(String[] args) throws InterruptedException {
        NioEventLoopGroup group = new NioEventLoopGroup();
        // 1. 创建启动器类
        ChannelFuture channelFuture = new Bootstrap()
                // 2. 添加eventLoop
                .group(group)
                // 3. 客户端channel实现
                .channel(NioSocketChannel.class)
                // 4. 添加处理器
                .handler(new ChannelInitializer<NioSocketChannel>() {
                    // 建立连接后调用
                    @Override
                    protected void initChannel(NioSocketChannel nsc) throws Exception {
                        nsc.pipeline().addLast(new LoggingHandler(LogLevel.DEBUG));
                        nsc.pipeline().addLast(new StringEncoder());
                    }
                })
                // 5.连接到服务器，connect 是异步非阻塞的,main线程发起，真正执行connect是nio线程
                .connect(new InetSocketAddress("localhost", 8080));
        channelFuture.sync();
        Channel channel = channelFuture.channel();
        // 处理用户数据
        new Thread(() -> {
            Scanner scanner = new Scanner(System.in);
            while(true){
                String line = scanner.nextLine();
                if("quit".equals(line)){
                    channel.close();
                    // 在处理关闭后的操作在此处不合理，因为 close 是异步的
//                    log.info("处理关闭后的操作");
                    break;
                }
                channel.writeAndFlush(line);
            }
        },"input").start();
        // 获取 CloseFuture 对象 1) 同步处理关闭  2) 异步处理关闭
        ChannelFuture closeFuture = channel.closeFuture();
        // 同步处理
/*        System.out.println("wait close....");
        closeFuture.sync();
        log.info("处理关闭的操作");*/


        // 异步处理
        closeFuture.addListener(new ChannelFutureListener() {
            @Override
            public void operationComplete(ChannelFuture future) throws Exception {
                log.info("处理关闭的操作");
                // 优雅关机
                group.shutdownGracefully();
            }
        });
    }
}
